package com.hll.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hll.api.config.web.RespMessage;
import com.hll.api.entity.User;
import com.hll.api.exception.MyException;
import com.hll.api.mapper.UserMapper;
import com.hll.api.service.UserService;
import org.apache.tomcat.jni.Status;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author Administrator
 * @create 2019-06-23 20:10
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    private final
    RedisTemplateService redisTemplateService;
    private final
    UserMapper mapper;
    @Autowired
    public UserServiceImpl(UserMapper mapper, RedisTemplateService redisTemplateService) {
        this.mapper = mapper;
        this.redisTemplateService = redisTemplateService;
    }
    private static final String TOKEN_USER="userToken";


    @Override
    public User getName(String name) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("email",name);
        return mapper.selectOne( wrapper );
    }

    @Override
    public User getUser(HttpServletRequest request) {
        String header = request.getHeader( TOKEN_USER );
        if (header!=null){
            try {
                User user = redisTemplateService.get( header, User.class );
                if (user!=null){
                    user.setPass("");
                }
                return user;
            }catch (Exception e){
                return null;
            }
        }
        return null;
    }

    @Override
    public User getMobile(String mobile) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile",mobile);
        return mapper.selectOne(wrapper);
    }

    @Override
    public User getXinhuaUser(HttpServletRequest request) {
        HttpSession session = request.getSession();
        Object id = session.getAttribute(User.USER_SESSION);
        if (id==null){
            throw new MyException(RespMessage.Status.NON_PERMISSION,"登录失效,请重新登录");
        }
        User user = mapper.selectById((Long) id);
        if (user==null){
            throw new MyException(RespMessage.Status.NON_PERMISSION,"用户不存在");
        }
        return mapper.selectById((Long) id);
    }
}
